var app = getApp();
var vp = require('../../resource/js/vp.js');
Page({
  data: {
    // 常见疾病
    commonDiseases: [
      { name: '高血压' }, { name: '脑卒中' }, { name: '冠心病' }, 
      { name: '糖尿病' }, { name: '脂肪肝' }, { name: '慢性肺病' },
      { name: '哮喘' }, { name: '骨质疏松' }, { name: '血脂异常' },
      { name: '恶性肿瘤' }, { name: '尿酸升高' }
    ],
    
    // 常见过敏源
    commonAllergens: [
      { name: '青霉素' }, { name: '磺胺类' }, { name: '维生素' },
      { name: '头孢类' }, { name: '鸡蛋' }, { name: '牛奶' },
      { name: '海鲜' }, { name: '花粉' }, { name: '尘螨' },
      { name: '粉尘' }, { name: '洗洁剂' }, { name: '化妆品' }
    ],
    
    // 用药选项
    minDate: '2025-01-01',
        maxDate: '2090-12-31',
        currentDateIndex: -1,
        
        // 用药方案选项
        medicationPlans: [
          { type: 'daily', name: '每天几次' },
          { type: 'days', name: '几天一次' },
          { type: 'hours', name: '几小时一次' }
        ],
        
        // 剂量单位
        dosageUnits: [
          { label: '片', value: '片' },
          { label: '克', value: '克' },
          { label: '毫克', value: '毫克' },
          { label: '毫升', value: '毫升' },
          { label: 'IU', value: 'IU' },
          { label: '杯', value: '杯' },
          { label: '软', value: '软' },
          { label: '粒', value: '粒' },
          { label: '颗', value: '颗' },
          { label: '袋', value: '袋' },
          { label: '支', value: '支' },
          { label: '瓶', value: '瓶' },
          { label: '滴', value: '滴' },
          { label: '匙', value: '匙' },
          { label: '喷', value: '喷' },
          { label: '吸', value: '吸' },
          { label: '包', value: '包' },
          { label: '微克', value: '微克' }
        ],
        
        // 剂量弹窗相关
        showDosageDialog: false,
        currentDosage: {
          value: '',
          unit: ''
        },
        currentDosageIndex: -1,
		plansNums:[],
    // 既往史数据
    pastData: {
      disease: {
        hasDisease: 'no',
        selectedCommon: [],
        customDiseases: []
      },
      surgery: {
        hasSurgery: 'no',
        surgeries: []
      },
      allergy: {
        hasAllergy: 'no',
        selectedCommon: [],
        customAllergens: []
      },
      medication: {
        hasMedication: 'no',
        medications: []
      }
    }
  },

  onLoad(options) {
    // 可以在这里初始化已保存的数据
	this.getFrequencyOptions = this.getFrequencyOptions.bind(this);
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('sendData', (data) => {
      this.setData({
        pastData: data.data || this.data.pastData
      });
    });
  },

  // 疾病史相关方法
  toggleDisease(e) {
    const value = e.currentTarget.dataset.value;
    this.setData({
      'pastData.disease.hasDisease': value
    });
  },

getCommonDisease:function(){
	  var that = this
	    app.util.request({
	  	  url: 'Familydoctor/getCommonDisease',
	  	  data: {
	  	  },
	  	  success(res) {
	  		  var data = res.data.data;
			  console.log('familyData',data)
	  		  that.setData({
	  			  'commonDiseases':data || this.data.commonDiseases
	  		  })
	  	  }
	    })
  },
  getCommonAllergens:function(){
  	  var that = this
  	    app.util.request({
  	  	  url: 'Familydoctor/getCommonAllergens',
  	  	  data: {
  	  	  },
  	  	  success(res) {
  	  		  var data = res.data.data;
  			  console.log('getCommonAllergens',data)
  	  		  that.setData({
  	  			  'commonAllergens':data || this.data.commonAllergens
  	  		  })
  	  	  }
  	    })
  },
  addDisease(e) {
	  const { name } = e.currentTarget.dataset;
	  console.log('name:',name)
    const newDiseases = [...this.data.pastData.disease.customDiseases, {
      id: Date.now(),
      name: name,
      diagnoseTime: ''
    }];
    
    this.setData({
      'pastData.disease.customDiseases': newDiseases
    });
  },

  inputDiseaseName(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({
      [`pastData.disease.customDiseases[${index}].name`]: e.detail.value
    });
  },

  changeDiagnoseTime(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({
      [`pastData.disease.customDiseases[${index}].diagnoseTime`]: e.detail.value
    });
  },

  removeDisease(e) {
    const { index } = e.currentTarget.dataset;
    wx.showModal({
      title: '确认删除',
      content: '确定要删除此疾病记录吗？',
      success: (res) => {
        if (res.confirm) {
          const newDiseases = [...this.data.pastData.disease.customDiseases];
          newDiseases.splice(index, 1);
          this.setData({
            'pastData.disease.customDiseases': newDiseases
          });
        }
      }
    });
  },

  // 手术史相关方法
  toggleSurgery(e) {
    const value = e.currentTarget.dataset.value;
    this.setData({
      'pastData.surgery.hasSurgery': value
    });
  },

  addSurgery() {
    const newSurgeries = [...this.data.pastData.surgery.surgeries, {
      id: Date.now(),
      name: '',
      date: '',
      hospital: ''
    }];
    
    this.setData({
      'pastData.surgery.surgeries': newSurgeries
    });
  },

  inputSurgeryName(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({
      [`pastData.surgery.surgeries[${index}].name`]: e.detail.value
    });
  },

  changeSurgeryDate(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({
      [`pastData.surgery.surgeries[${index}].date`]: e.detail.value
    });
  },

  inputSurgeryHospital(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({
      [`pastData.surgery.surgeries[${index}].hospital`]: e.detail.value
    });
  },

  removeSurgery(e) {
    const { index } = e.currentTarget.dataset;
    wx.showModal({
      title: '确认删除',
      content: '确定要删除此手术记录吗？',
      success: (res) => {
        if (res.confirm) {
          const newSurgeries = [...this.data.pastData.surgery.surgeries];
          newSurgeries.splice(index, 1);
          this.setData({
            'pastData.surgery.surgeries': newSurgeries
          });
        }
      }
    });
  },

  // 过敏史相关方法
  toggleAllergy(e) {
    const value = e.currentTarget.dataset.value;
    this.setData({
      'pastData.allergy.hasAllergy': value
    });
  },


  addAllergen(e) {
	  const { name } = e.currentTarget.dataset;
    const newAllergens = [...this.data.pastData.allergy.customAllergens, {
      id: Date.now(),
      name: name,
      symptom: ''
    }];
    
    this.setData({
      'pastData.allergy.customAllergens': newAllergens
    });
  },

  inputAllergenName(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({
      [`pastData.allergy.customAllergens[${index}].name`]: e.detail.value
    });
  },

  inputAllergenSymptom(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({
      [`pastData.allergy.customAllergens[${index}].symptom`]: e.detail.value
    });
  },

  removeAllergen(e) {
    const { index } = e.currentTarget.dataset;
    wx.showModal({
      title: '确认删除',
      content: '确定要删除此过敏源记录吗？',
      success: (res) => {
        if (res.confirm) {
          const newAllergens = [...this.data.pastData.allergy.customAllergens];
          newAllergens.splice(index, 1);
          this.setData({
            'pastData.allergy.customAllergens': newAllergens
          });
        }
      }
    });
  },

  // 用药史相关方法
  toggleMedication(e) {
    const value = e.currentTarget.dataset.value;
    this.setData({
      'pastData.medication.hasMedication': value
    });
  },
// 获取动态的用药次数选项
  getFrequencyOptions(type) {
	  console.log(type)
	  if (!type) return ['请先选择用药方案'];
	      
	      if (type === 'daily') {
	        return Array.from({length: 4}, (_, i) => `每天${i+1}次`);
	      } else if (type === 'days') {
	        return Array.from({length: 30}, (_, i) => `${i+1}天一次`);
	      } else if (type === 'hours') {
	        return Array.from({length: 24}, (_, i) => `${i+1}小时一次`);
	      }
	      return [];
  },

  // 修改开始日期
  changeStartDate(e) {
    const { index } = e.currentTarget.dataset;
	console.log('index:',index)
    this.setData({
      [`pastData.medication.medications[${index}].startDate`]: e.detail.value
    });
  },
  
  // 修改结束日期
  changeEndDate(e) {
    const { index } = e.currentTarget.dataset;
	console.log('index:',index)
    this.setData({
      [`pastData.medication.medications[${index}].endDate`]: e.detail.value
    });
  },

  // 修改用药方案
  changeMedicationPlan(e) {
    const { index } = e.currentTarget.dataset;
        const planIndex = e.detail.value;
        const plan = this.data.medicationPlans[planIndex];
        console.log('index:',index)
		console.log('planIndex:',planIndex)
        // 更新方案并重置频率
        const medications = this.data.pastData.medication.medications;
        medications[index].planIndex = planIndex;
        medications[index].plan = plan;
        medications[index].frequency = '';
        medications[index].frequencyIndex = 0;
	
        console.log(this.getFrequencyOptions(plan.type))
        // 使用setData确保视图更新
        this.setData({
          'pastData.medication.medications': medications,
		  'plansNums':this.getFrequencyOptions(plan.type)
        });
  },

  changeMedicationFrequency(e) {
    const { index } = e.currentTarget.dataset;
    const frequencyIndex = e.detail.value;
	console.log(index)
	console.log(frequencyIndex)
	console.log(this.data.plansNums)
	console.log(this.data.plansNums[frequencyIndex])
    this.setData({
      [`pastData.medication.medications[${index}].frequencyIndex`]: frequencyIndex,
      [`pastData.medication.medications[${index}].frequency`]: this.data.plansNums[frequencyIndex]
    });
  },
  // 显示剂量弹窗
  showDosageDialog(e) {
    const index = e.currentTarget.dataset.index;
    const dosage = this.data.pastData.medication.medications[index].dosage || {};
    
    this.setData({
      showDosageDialog: true,
      currentDosageIndex: index,
      currentDosage: {
        value: dosage.value || '',
        unit: dosage.unit || ''
      }
    });
  },

  // 隐藏剂量弹窗
  hideDosageDialog() {
    this.setData({
      showDosageDialog: false
    });
  },

  // 输入剂量值
  inputDosageValue(e) {
    this.setData({
      'currentDosage.value': e.detail.value
    });
  },

  // 选择剂量单位
  selectDosageUnit(e) {
    const unit = e.currentTarget.dataset.value;
    this.setData({
      'currentDosage.unit': unit
    });
  },

  // 确认剂量
  confirmDosage() {
    const index = this.data.currentDosageIndex;
    this.setData({
      [`pastData.medication.medications[${index}].dosage`]: {
        value: this.data.currentDosage.value,
        unit: this.data.currentDosage.unit
      },
      showDosageDialog: false
    });
  },

  addMedication() {
    const newMedications = [...this.data.pastData.medication.medications, {
          id: Date.now(),
          name: '',
          startDate: '',
          endDate: '',
          plan: { type: '', name: '' },
          planIndex: 0,
          frequency: '',
          frequencyIndex: 0,
          dosage: {
            value: '',
            unit: ''
          }
        }];
        
        this.setData({
          'pastData.medication.medications': newMedications
        });
  },

  inputMedicationName(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({
      [`pastData.medication.medications[${index}].name`]: e.detail.value
    });
  },


  inputMedicationDosage(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({
      [`pastData.medication.medications[${index}].dosage`]: e.detail.value
    });
  },

  removeMedication(e) {
    const { index } = e.currentTarget.dataset;
    wx.showModal({
      title: '确认删除',
      content: '确定要删除此药品记录吗？',
      success: (res) => {
        if (res.confirm) {
          const newMedications = [...this.data.pastData.medication.medications];
          newMedications.splice(index, 1);
          this.setData({
            'pastData.medication.medications': newMedications
          });
        }
      }
    });
  },

  // 保存数据
  save() {
    // 验证必填项
    if (this.data.pastData.disease.hasDisease === 'yes') {
      for (let i = 0; i < this.data.pastData.disease.customDiseases.length; i++) {
        const disease = this.data.pastData.disease.customDiseases[i];
        if (!disease.name || !disease.diagnoseTime) {
          wx.showToast({
            title: `请完善疾病${i + 1}的信息`,
            icon: 'none'
          });
          return;
        }
      }
    }
    
    if (this.data.pastData.surgery.hasSurgery === 'yes') {
      for (let i = 0; i < this.data.pastData.surgery.surgeries.length; i++) {
        const surgery = this.data.pastData.surgery.surgeries[i];
        if (!surgery.name || !surgery.date) {
          wx.showToast({
            title: `请完善手术${i + 1}的信息`,
            icon: 'none'
          });
          return;
        }
      }
    }
    
    if (this.data.pastData.allergy.hasAllergy === 'yes') {
      for (let i = 0; i < this.data.pastData.allergy.customAllergens.length; i++) {
        const allergen = this.data.pastData.allergy.customAllergens[i];
        if (!allergen.name) {
          wx.showToast({
            title: `请完善过敏源${i + 1}的信息`,
            icon: 'none'
          });
          return;
        }
      }
    }
    
    if (this.data.pastData.medication.hasMedication === 'yes') {
      for (let i = 0; i < this.data.pastData.medication.medications.length; i++) {
        const med = this.data.pastData.medication.medications[i];
		console.log(med)
        if (!med.name || !med.endDate || !med.startDate || !med.plan || !med.frequency || !med.dosage) {
          wx.showToast({
            title: `请完善药品${i + 1}的信息`,
            icon: 'none'
          });
          return;
        }
      }
    }
    
    // 保存逻辑
    const requestData = {
          pastData: this.data.pastData
        };
		console.log('requestData',requestData)
        // 保存逻辑
        const that = this;
          // 模拟保存操作
          wx.showLoading({
            title: '保存中...',
          });
    		let activeUser = wx.getStorageSync('activeUser')
    		requestData.type = 3;    		
    		requestData.family_id = activeUser.id
          let jsonData = JSON.stringify(requestData);
          app.util.request({
          	url: 'Familydoctor/createPastData',
          	data: jsonData,
          	method:'POST',
          	headers: {
          		'Content-Type': 'application/json',
          	},
          	success(res) {
          		console.log(res)
          		if(res.data.code){	
    				wx.hideLoading();
    				wx.showToast({
    				  title: '保存成功',
    				  icon: 'success'
    				});
    				that.setData({
    				  isEditing: false
    				});
    				
    				const eventChannel = that.getOpenerEventChannel();
    				eventChannel.emit('sendData', res.data.data.content);
    				setTimeout(() => {
    				  wx.navigateBack();
    				}, 1500);
          		}else{
          			wx.showToast({ title: '提交失败请重试' });
          		}
          	}
          })
  }
});